package com.coolgor.coldot.service.wechat.qyh.impl;

import java.util.ArrayList;
import java.util.List;

import com.coolgor.coldot.common.PageCalculator;
import com.coolgor.coldot.dao.auth.LocalUserDao;
import com.coolgor.coldot.dao.wechat.qyh.QYHUserDao;
import com.coolgor.coldot.dto.wechat.qyh.QYHUserExecution;
import com.coolgor.coldot.entity.auth.LocalUser;
import com.coolgor.coldot.entity.wechat.qyh.QYHUser;
import com.coolgor.coldot.enums.wechat.qyh.QYHUserStateEnum;
import com.coolgor.coldot.exceptions.auth.LocalUserOperationException;
import com.coolgor.coldot.exceptions.wechat.qyh.QYHUserOperationException;
import com.coolgor.coldot.service.wechat.qyh.QYHUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class QYHUserServiceImpl implements QYHUserService {
	private static Logger log = LoggerFactory.getLogger(QYHUserServiceImpl.class);

	@Autowired
	private QYHUserDao qyhUserDao;
	
	@Autowired
	private LocalUserDao localUserDao;

	@Override
	public QYHUser getQYHUser(String userid, String corpid) {
		return qyhUserDao.queryQYHUser(userid, corpid);
	}

	@Override
	public QYHUserExecution getQYHUserList(QYHUser qyhUserCondition, int pageIndex, int pageSize) {
		//将页码转换成行码
		int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
		//依据查询条件，调用dao层返回相关的查询结果列表
		List<QYHUser> qyhUserList = qyhUserDao.queryQYHUserList(qyhUserCondition, rowIndex, pageSize);
		//依据相同的查询条件，返回查询结果总数
		int count = qyhUserDao.queryQYHUserCount(qyhUserCondition);
		QYHUserExecution result = new QYHUserExecution();
		if (qyhUserList != null) {
			result.setState(QYHUserStateEnum.SUCCESS.getState());
			result.setStateInfo(QYHUserStateEnum.SUCCESS.getStateInfo());
			result.setQyhUserList(qyhUserList);
			result.setCount(count);
		} else {
			result.setState(QYHUserStateEnum.INNER_ERROR.getState());
		}
		return result;
	}

	@Override
	@Transactional
	public QYHUserExecution addQYHUser(QYHUser qyhUser) throws QYHUserOperationException {
		// 空值判断
		if (qyhUser == null) {
			return new QYHUserExecution(QYHUserStateEnum.NULL_USER);
		}
		int effectedNum;
		try {
			// 判断数据库中是否有corpid相同且userid相同的数据
			QYHUser checkuser = new QYHUser();
			checkuser.setUserid(qyhUser.getUserid());
			checkuser.setCorpid(qyhUser.getCorpid());
			effectedNum = qyhUserDao.queryQYHUserCount(checkuser);
			if (effectedNum > 0) {
				//如果存在corpid相同且userid相同的数据
				//直接返回执行结果，而不进行后面添加的操作
				return new QYHUserExecution(QYHUserStateEnum.EXISTUSERINFO);
			} 
			// 添加
			effectedNum = qyhUserDao.insertQYHUser(qyhUser);
			if (effectedNum <= 0) {
				throw new QYHUserOperationException("微信企业号用户信息录入失败");
			} 
		} catch (Exception e) {
			throw new QYHUserOperationException("addQYHUser error:" + e.getMessage());
		}
		return new QYHUserExecution(QYHUserStateEnum.SUCCESS, qyhUser);
	}

	@Override
	@Transactional
	public QYHUserExecution modifyQYHUser(QYHUser qyhUser) throws QYHUserOperationException {
		// 空值判断
		if (qyhUser == null) {
			return new QYHUserExecution(QYHUserStateEnum.NULL_USER);
		}
		// 判断是否存在userid和corpid都匹配的数据
		QYHUser checkQYHUser = qyhUserDao.queryQYHUser(qyhUser.getUserid(), qyhUser.getCorpid());
		if ( null == checkQYHUser ) {
			//判断这个ID下是否有用户，如果没有则返回空用户状态
			return new QYHUserExecution(QYHUserStateEnum.NULL_USER);
		}
		// 判断是否有更改本地唯一用户标识userID
		// 如果更改了userID，则判断新的userID是否真的存在该本地用户
		if (checkQYHUser.getUserID()!=qyhUser.getUserID() && checkQYHUser.getUserID()!=0L) {
			LocalUser checkLocalUser = localUserDao.queryLocalUserById(qyhUser.getUserID());
			if ( null == checkLocalUser ) {
				//判断这个ID下是否有用户，如果没有则返回抛出异常
				throw new LocalUserOperationException("关联本地用户不存在");
			}
		}
		// 即将更新用户信息
		int effectedNum;
		try {
			effectedNum = qyhUserDao.updateQYHUser(qyhUser);
			if (effectedNum <= 0) {
				throw new QYHUserOperationException("企业号用户信息更新失败");
			} 
		} catch (Exception e) {
			throw new QYHUserOperationException("Modify QYHUser error:" + e.getMessage());
		}
		return new QYHUserExecution(QYHUserStateEnum.SUCCESS, qyhUser);
	}

	@Override
	@Transactional
	public QYHUserExecution removeQYHUser(QYHUser qyhUser) throws QYHUserOperationException {
		// 空值判断
		if (qyhUser == null) {
			return new QYHUserExecution(QYHUserStateEnum.NULL_USER);
		}
		int effectedNum;
		try {
			// 执行删除操作
			effectedNum = qyhUserDao.deleteQYHUser(qyhUser);
			if (effectedNum <= 0) {
				throw new QYHUserOperationException("企业号用户信息删除失败");
			} 
		} catch (Exception e) {
			throw new QYHUserOperationException("Delete QYHUser error:" + e.getMessage());
		}
		return new QYHUserExecution(QYHUserStateEnum.SUCCESS, qyhUser);
	}

	@Override
	@Transactional
	public QYHUserExecution batchRemoveQYHUser(List<QYHUser> qyhUserList) throws QYHUserOperationException {
		// 空值判断
		if (qyhUserList == null) {
			return new QYHUserExecution(QYHUserStateEnum.EMPTY_LIST);
		}
		List<Long> qyhUserIDList = new ArrayList<Long>();
		for (int i=0; i<qyhUserList.size(); i++) {
			qyhUserIDList.add(qyhUserList.get(i).getUserID());			
		}
		int effectedNum;
		try {
			// 执行删除操作
			effectedNum = qyhUserDao.batchDeleteQYHUser(qyhUserIDList);
			if (effectedNum <= 0) {
				throw new QYHUserOperationException("微信企业号用户信息批量删除失败");
			} 
		} catch (Exception e) {
			throw new QYHUserOperationException("Delete LocalUser error:" + e.getMessage());
		}
		QYHUserExecution ue = new QYHUserExecution(QYHUserStateEnum.SUCCESS);
		//将删除的记录总数加入到返回值
		ue.setCount(effectedNum);
		return ue;
	}

}
